<template>
  <div>
    <!-- 添加按钮 -->
    <el-button type="primary" icon="el-icon-plus" style="margin:10px 0" @click="addTrade">添加</el-button>
    <!-- 表格 -->
    <el-table style="width: 100%" border :data="list">
      <el-table-column type="index" prop="prop" label="序号" width="100px" align="center"></el-table-column>
      <el-table-column prop="tmName" label="品牌名称" width="width"></el-table-column>
      <el-table-column prop="logoUrl" label="品牌LOGO" width="width">
        <!-- 使用el封装好的作用域插槽，用来插入图片 -->
        <template slot-scope="{row,$index}">
          <img :src="row.logoUrl" alt="暂无" style="width: 100px;height: 100px;" />
        </template>
      </el-table-column>
      <el-table-column prop="prop" label="操作" width="width">
        <template slot-scope="{row,$index}">
          <el-button type="warning" icon="el-icon-edit" size="mini" @click="updateTrade(row)">修改</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteTrade(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      style="margin-top:20px; text-align:center"
      :current-page="page"
      :page-sizes="[3, 5, 10]"
      :page-size="limit"
      layout="  prev, pager, next, jumper,->,total,sizes"
      :total="total"
      :pager-count="5"
      @current-change="getPageList"
      @size-change="sizeChange"
    ></el-pagination>
    <!-- 点击添加/修改，弹出的表单 -->
    <el-dialog :title="tmForm.id?'品牌修改':'品牌添加'" :visible.sync="dialogFormVisible">
      <!-- 
        model属性用于将表单数据，收集到 tmForm上 
        rules属性，用于进行表单验证
      -->
      <el-form style="width: 80%;" :model="tmForm" :rules="rules" ref="ruleForm">
        <!-- prop属性，用于表单验证的标识 -->
        <el-form-item label="品牌名称" :label-width="formLabelWidth" prop="tmName">
          <el-input autocomplete="off" v-model="tmForm.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" :label-width="formLabelWidth" prop="logoUrl">
          <!-- 
            action属性：图片上传的地址 ,注意前面要加上 /dev-api
            /dev-api/admin/product/fileUpload
            on-success：图片上传成功时，执行一次
            before-upload：图片上传前执行
          -->
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <!-- 使用封装好的具名插槽，否则会出现在虚线框内 -->
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，不超过5m</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateTrade">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'TradeMark',
  data() {
    return {
      page: 1,
      limit: 5,
      total: 0,
      list: [],
      dialogFormVisible: false,
      formLabelWidth: '100px',
      // 用于收集品牌信息，注意属性名要与接收数据的后端统一
      tmForm: {
        tmName: '',
        logoUrl: ''
      },
      // 表单验证规则
      rules: {
        tmName: [
          // blur：失焦时进行验证；change：表单元素更改时进行验证
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'change' }
        ],
        logoUrl: [{ required: true, message: '请上传图片' }]
      }
    }
  },
  methods: {
    // 表格显示
    async getPageList(pager = this.page) {
      this.page = pager
      const { page, limit } = this
      const result = await this.$API.trademark.reqTradeMarkList(page, limit)
      // console.log(page, limit, result)
      if (result.code === 200) {
        this.total = result.data.total
        this.list = result.data.records
      }
    },
    sizeChange(limit) {
      this.limit = limit
      this.getPageList()
    },
    // 增、删、改操作
    addTrade() {
      this.dialogFormVisible = true
      this.tmForm = { tmName: '', logoUrl: '' }
    },
    updateTrade(row) {
      this.dialogFormVisible = true
      // 将获取到的信息，赋给表单
      // 为防止双向绑定导致表格数据的改变，必须使用浅拷贝，而不是更改地址
      this.tmForm = { ...row }
    },
    deleteTrade(row) {
      this.$confirm(`此操作将永久删除${row.tmName}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        // 点击确定时触发
        .then(async () => {
          // 向服务器发请求
          const result = await this.$API.trademark.reqDeleteTradeMark(row.id)
          if (result.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
          this.getPageList(this.list.length > 1 ? this.page : this.page - 1)
        })
        // 点击取消时触发
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 图片上传相关：成功、上传前
    handleAvatarSuccess(res, file) {
      // 若上传成功，则 res.data返回服务器上的图片地址
      // this.tmForm.logoUrl = res.data
      console.log(res)
      this.tmForm.logoUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 5

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 确认添加/修改时调用
    addOrUpdateTrade() {
      // 验证通过时，再执行更新/添加操作
      this.$refs.ruleForm.validate(async success => {
        // 如果返回为true，即通过了表单验证
        if (success) {
          this.dialogFormVisible = false
          // 发请求
          const result = await this.$API.trademark.reqAddOrUpdateTradeMark(this.tmForm)
          if (result.code === 200) {
            this.$message({
              type: 'success',
              message: this.tmForm.id ? '修改品牌信息成功' : '添加品牌信息成功'
            })
            // 更新列表，并定向至当前页
            this.getPageList(this.page)
          }
        } else {
          console.log('表单有误，请修改！！！')
          this.$message({
            type: 'error',
            message: '表单有误，请修改！！！'
          })
          return false
        }
      })
    }
  },
  mounted() {
    this.getPageList()
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
